import tkinter as tk
from tkinter import messagebox
import random
import json

class EnglishWordStudy:
    def __init__(self):
        self.word_dictionary = {}
        with open("word_list.json", "r", encoding="utf-8") as file:
            self.word_dictionary = json.load(file)
        file.close()

    def add_word(self, word, meaning):
        self.word_dictionary[word] = {
            "word": word,
            "meaning": meaning,
        }

    def get_random_word(self):
        if self.word_dictionary:
            return random.choice(list(self.word_dictionary.keys()))
        else:
            return None

    def search_word(self, word):
        print(word)
        if word in self.word_dictionary:
            return word, self.word_dictionary[word]["meaning"]
        else:
            return "Word not found in the dictionary."

    def save_words_to_file(self):
        with open("word_list.json", "w", encoding="utf-8") as file:
            json.dump(self.word_dictionary, file, indent=4)
        file.close()

word_study = EnglishWordStudy()

def add_word():
    word = entry_word.get()
    meaning = entry_meaning.get()
    if word.strip() and meaning.strip():
        word_study.add_word(word, meaning)
        word_study.save_words_to_file()
        messagebox.showinfo("Word Added", f"Word '{word}' added successfully.")
    else:
        messagebox.showerror("Error", "Both word and meaning are required.")

def show_random_word():
    random_word = word_study.get_random_word()
    if random_word:
        meaning = word_study.word_dictionary[random_word]
        messagebox.showinfo("Random Word", f"Word: {random_word}\nMeaning: {meaning}")
    else:
        messagebox.showwarning("No Words", "There are no words in the dictionary.")

def search_word():
    word = entry_word_search.get()
    result = word_study.search_word(word)
    messagebox.showinfo("Search Result", f"{result}")


root = tk.Tk()
root.title("English Word Study")

label_instruction = tk.Label(root, text="Choose an option:")
label_instruction.pack()

frame_add_word = tk.Frame(root)
frame_add_word.pack()

label_word = tk.Label(frame_add_word, text="Word:")
label_word.pack(side=tk.LEFT)

entry_word = tk.Entry(frame_add_word)
entry_word.pack(side=tk.LEFT)

label_meaning = tk.Label(root, text="Meaning:")
label_meaning.pack()

entry_meaning = tk.Entry(root, width = 100)
entry_meaning.pack()

button_add_word = tk.Button(root, text="Add Word", command=add_word)
button_add_word.pack()

button_random_word = tk.Button(root, text="Get Random Word", command=show_random_word)
button_random_word.pack()

frame_search = tk.Frame(root)
frame_search.pack()

label_search = tk.Label(frame_search, text="Search for a word:")
label_search.pack(side=tk.LEFT)

entry_word_search = tk.Entry(frame_search)
entry_word_search.pack(side=tk.LEFT)

button_search = tk.Button(frame_search, text="Search", command=search_word)
button_search.pack(side=tk.LEFT)

root.mainloop()
